<?php defined('SYSPATH') or die('No direct access allowed.');

class Controller_Admin_Article extends Controller_Admin_Template
{
    
    
    public function action_index()
    {                                      
  	$count = DB::query(Database::SELECT, "SELECT COUNT(*) as `count` FROM `articles`")
                    ->execute()
                    ->get('count');
        
  	$pagination = Pagination::factory(array('total_items' => $count));
        
    $articles = DB::query(Database::SELECT, "SELECT * FROM `articles`
                                                 ORDER BY `modified` DESC
                                                 LIMIT :offset, :limit")
                        ->param(':offset', $pagination->offset)
                        ->param(':limit', $pagination->items_per_page)
                        ->as_object()
                        ->execute();                
              
  	 $page_links = $pagination->render(); 
        
    $this->template->content = View::factory('admin/article/article')
                                    ->set('articles', $articles)
                                    ->set('page_links', $page_links);
        
    }
    
    public function action_add()
    {
                
        $this->template->content = View::factory('admin/article/form')
                                        ->set('title', 'Добавление статьи')
                                        ->set('article', array());                                       
    }
    
    public function action_edit()
    {
        $id = Arr::get($_REQUEST, 'id', -1);       

        $article = ORM::factory('article', $id);
        if($article->loaded()){           
            $article = $article->as_array();
        
            $this->template->content = View::factory('admin/article/form')     
                                           ->set('title', 'Редактирование статьи')
                                           ->set('article', $article);
                                           
        } else        
            Request::$initial->redirect('admin/article');
    }
    
    public function action_save()
    {
        $this->auto_render = false;
        
        $id = Arr::get($_POST, 'id', NULL);
        
        if(!empty($id)){
            $article = ORM::factory('article', $id);
            
            $old_href = $article->href;
            
            $article->values($_POST)
                    ->set('modified', DB::expr('NOW()'));
            
        } else {
            $article = ORM::factory('article')
                            ->values($_POST)
                            ->set('created', DB::expr('NOW()'))
                            ->set('modified', DB::expr('NOW()'));
        }
        
        try
        {           
            $article->save();
  
            
            if(isset($old_href))
                DB::query(Database::UPDATE, "UPDATE `chapters` SET `href`=:new_href WHERE `href`=:old_href")
                    ->param(':new_href', $article->href)
                    ->param(':old_href', $old_href)
                    ->execute();

            $response = array('status' => 'ok');
        }
        catch(Kohana_ORM_Validation_Exception $e)
        {
            $errors = $e->errors('/admin');
            $response = array('status' => 'error',
                              'error' => $errors);
        }
     
        $this->response->body(json_encode($response));        
    }
    
    public function action_del()
    {
        $id = Arr::get($_GET, 'id', 0);
        try
        {
            ORM::factory('article', $id)->delete();
        }
        catch(Exception $e){}
        
        Request::$initial->redirect(Request::$initial->referrer());
    }
}